package com.controller;

import com.base.BaseController;
import com.constant.HandleEnum;
import com.minio.service.MinIOService;
import com.req.ArticalReq;
import com.req.ArticalPageReq;
import com.res.ArticalRes;
import com.base.BasePageRes;
import com.res.UserRes;
import com.service.ArticalService;
import com.service.impl.ArticalServiceImpl;
import com.util.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/artical")
@Api(tags = "帖子")
@Slf4j
public class ArticalController extends BaseController {
    @Autowired
    private ArticalServiceImpl articalService;
    @Autowired
    private MinIOService minIOService;
    @PostMapping("/save")
    @ApiOperation("帖子的增删改查")
    public R<ArticalRes> saveArtical(@RequestBody ArticalReq articalReq){

        if(!Objects.equals(articalReq.getHandle(), HandleEnum.QUERY.getCode())) {
            if(StringUtils.isEmpty(articalReq.getUserId())) {
                UserRes user = this.getUser();
                articalReq.setUserId(user.getId());
            }
        }
        return R.ok(articalService.saveArtical(articalReq));
    }

    @PostMapping("/uploadFilePublish")
    @ApiOperation("上传文件发贴")
    public R<ArticalRes> uploadFilePublish(HttpServletRequest request,ArticalReq articalReq) throws Exception{
        MultipartHttpServletRequest multipartRequest =
                WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();

        Map<String,List<MultipartFile>> fileMap = new HashMap<>();
        for (Map.Entry<String, List<MultipartFile>> entry : multiFileMap.entrySet()) {
            fileMap.put(entry.getKey(),entry.getValue());
        }
        Map<String, String> fileUriMap = minIOService.upFile(fileMap, "bbs", null);
        articalReq.setImgs(fileUriMap.get("upimgs"));
        articalReq.setPreImg(fileUriMap.get("uppreImg"));
        articalReq.setResourceFile(fileUriMap.get("upresourceFile"));
        if(StringUtils.isEmpty(articalReq.getHandle())){
            articalReq.setHandle(HandleEnum.ADD.getCode());
        }
        if(StringUtils.isEmpty(articalReq.getUserId())){
            articalReq.setUserId("imba1991");
        }
       return R.ok(articalService.saveArtical(articalReq));
    }
    @PostMapping("/netFilePublish")
    @ApiOperation("网络文件发贴")
    public R<ArticalRes> netFilePublish(@RequestBody ArticalReq articalReq) throws Exception{
        //判断标题是否重复
        if(articalService.countByField("title",articalReq.getTitle())>0){
            return R.error(String.format("标题重复:%s",articalReq.getTitle()));
        }
        //替换有指引的标题
        String[] titles = new String[]{"核基地"};
        for (String title : titles) {
            if(articalReq.getTitle().contains(title)){
                articalReq.setTitle(articalReq.getTitle().replace(title,""));
            }
        }
        Map<String,List<String>> netFileMap = new HashMap<>();
        netFileMap.put("netImgs",articalReq.getNetImgs());
        netFileMap.put("netpreImg",articalReq.getNetpreImg());
        netFileMap.put("netresourceFile",articalReq.getNetresourceFile());
        Map<String, String> fileUriMap = minIOService.netFile(netFileMap, "bbs", null,articalReq.getOrigin());
        if(!CollectionUtils.isEmpty(fileUriMap)) {
            articalReq.setImgs(fileUriMap.get("netImgs"));
            articalReq.setPreImg(fileUriMap.get("netpreImg"));
            articalReq.setResourceFile(fileUriMap.get("netresourceFile"));
        }
        if(StringUtils.isEmpty(articalReq.getHandle())){
            articalReq.setHandle(HandleEnum.ADD.getCode());
        }
        if(StringUtils.isEmpty(articalReq.getUserId())){
            articalReq.setUserId("imba1991");
        }
        return R.ok(articalService.saveArtical(articalReq));
    }

    @PostMapping("/batchNetFilePublish")
    @ApiOperation("网络文件批量发贴")
    public R<List<Long>> batchNetFilePublish(@RequestBody List<ArticalReq> articalReqs) throws Exception{
        if(CollectionUtils.isEmpty(articalReqs)){
            return R.error("空集合");
        }
        List<Long> ids = new ArrayList<>();
        for (ArticalReq articalReq : articalReqs) {
            //判断标题是否重复
            if(articalService.countByField("title",articalReq.getTitle())>0){
                return R.error(String.format("标题重复:%s",articalReq.getTitle()));
            }
            Map<String,List<String>> netFileMap = new HashMap<>();
            netFileMap.put("netImgs",articalReq.getNetImgs());
            netFileMap.put("netpreImg",articalReq.getNetpreImg());
            netFileMap.put("netresourceFile",articalReq.getNetresourceFile());
            Map<String, String> fileUriMap = minIOService.netFile(netFileMap, "bbs", null);
            if(!CollectionUtils.isEmpty(fileUriMap)) {
                articalReq.setImgs(fileUriMap.get("netImgs"));
                articalReq.setPreImg(fileUriMap.get("netpreImg"));
                articalReq.setResourceFile(fileUriMap.get("netresourceFile"));
            }
            if(StringUtils.isEmpty(articalReq.getHandle())){
                articalReq.setHandle(HandleEnum.ADD.getCode());
            }
            if(StringUtils.isEmpty(articalReq.getUserId())){
                articalReq.setUserId("imba1991");
            }
            ArticalRes articalRes = articalService.saveArtical(articalReq);
            ids.add(articalRes.getId());
        }
        return R.ok(ids);
    }


    /**
     * 这个适合人的接口，不适合首页的展示接口。
     * @param pageReq
     * @return
     */
    @PostMapping("/queryPage")
    @ApiOperation("文章分页查询")
    public R<BasePageRes> queryPage(@RequestBody ArticalPageReq pageReq){
        return R.ok(articalService.queryPage(pageReq,this.getUser()));
    }

    @PostMapping("/saves")
    @ApiOperation("批量采集接口")
    public R<ArticalRes> saveArtical(@RequestBody List<ArticalReq> articalReq){
        try {


            for (ArticalReq req : articalReq) {
                try {
                    this.saveArtical(req);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage());
        }
    }



}
